package com.cgc.venus.server.job.jobdetail;
import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.job.Constants;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 统计平台空间
 */
public class StatsNamespaceJob extends AbstractBaseJob {
    private static Logger logger = LoggerFactory.getLogger(StatsNamespaceJob.class);
    public StatsNamespaceJob() {
    }
    public void execute(JobExecutionContext context)  
        throws JobExecutionException {
        logger.info("统计平台空间job start...");
        List objs = new ArrayList<Object>();
        String sql="";
        String id="";
        try {
            //查询统计值
            sql="SELECT count(id) num FROM t_namespace UNION ALL SELECT count(id) num FROM t_namespace WHERE `status` = 0 UNION ALL SELECT count(id) num FROM t_namespace WHERE DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d')";
            List<Map<String, Object>> qr=getJdbcTemplate().queryForList(sql);
            //更新统计值表
            sql="select id from t_job_stats_namespace where date_format(create_time,'%Y-%m-%d')=date_format(NOW(),'%Y-%m-%d')";
            List<Map<String, Object>> l=getJdbcTemplate().queryForList(sql);
            if(l!=null&&l.size()>0){
                //db update
                id=l.get(0).get("id").toString();
                sql = "update t_job_stats_namespace  set ns_count_all=?,ns_count_stop=?,ns_count_today=?,last_update_time=NOW() where id=?";
            }else{
                //db insert
                id = StringUtil.getUUID();
                sql = "INSERT INTO t_job_stats_namespace(ns_count_all,ns_count_stop,ns_count_today,id,create_time,last_update_time) VALUES (?,?,?,?,NOW(),NOW())";
            }
            objs.add(qr.get(0).get("num"));
            objs.add(qr.get(1).get("num"));
            objs.add(qr.get(2).get("num"));
            objs.add(id);
            getJdbcTemplate().update(sql, objs.toArray());
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            handleEx("统计平台空间任务异常,异常信息:"+getErrorInfoFromException(ex),Constants.ALARM_TYPE_JOB_ERROR,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,Constants.ALARM_NS_ALL);
            throw new JobExecutionException(ex);
        }
    }  
}